package com.mdd.admin.service.account.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.account.IAccountLogService;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.vo.account.AccountLogListVo;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.account.AccountLog;
import com.mdd.common.enums.AccountEnum;
import com.mdd.common.mapper.account.AccountLogMapper;
import com.mdd.common.utils.StringUtil;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.UrlUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.Map;

/**
 * @author kn4im3
 * @date 2023/3/8 09:29
 */
@Service
public class AccountLogServiceImpl implements IAccountLogService {

    @Resource
    private AccountLogMapper accountLogMapper;

    /**
     * 余额信息列表
     *
     * @param pageParam 分页参数
     * @param params    参数
     * @return Object
     */
    @Override
    public PageResult<AccountLogListVo> list(PageParam pageParam, Map<String, String> params) {
        Integer pageNo = pageParam.getPageNo();
        Integer pageSize = pageParam.getPageSize();
        MPJQueryWrapper<AccountLog> mpjQueryWrapper = new MPJQueryWrapper<>();
        mpjQueryWrapper.selectAll(AccountLog.class)
                .select("u.nickname as nickname", "u.avatar as avatar", "u.sn as userSn", "u.username as username")
                .innerJoin("?_user u ON t.user_id = u.id".replace("?_", GlobalConfig.tablePrefix))
                .orderByDesc("t.id");
        if (StringUtil.isNotEmpty(params.get("userInfo"))) {
            String userInfo = params.get("userInfo");
            mpjQueryWrapper.nested(wq -> wq
                    .like("u.username", userInfo).or()
                    .like("u.nickname", userInfo).or()
                    .like("u.mobile", userInfo));
        }
        accountLogMapper.setSearch(mpjQueryWrapper, params, new String[]{
                "=:changeType@t.change_type:int",
                "datetime:startTime-endTime@t.create_time:str"
        });
        IPage<AccountLogListVo> iPage = accountLogMapper.selectJoinPage(
                new Page<>(pageNo, pageSize),
                AccountLogListVo.class,
                mpjQueryWrapper);
        LinkedList<AccountLogListVo> list = new LinkedList<>();
        iPage.getRecords().forEach(item -> {
            item.setChangeTypeDesc(AccountEnum.getMsgByCode(item.getChangeType()));
            item.setAvatar(UrlUtil.toAbsoluteUrl(item.getAvatar()));
            item.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            list.add(item);
        });
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }
}
